package com.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.config.WebSocketServer;
import com.demo.constant.Code;
import com.demo.entity.EquipmentData;
import com.demo.entity.ExcelData;
import com.demo.entity.ResModel;
import com.demo.mapper.EquipmentDataMapper;
import com.demo.service.EquipmentDataService;
import com.demo.util.EasyExcelUtils;
import com.rfid.bean.OutputDataInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 设备数据表 服务实现类
 * </p>
 *
 * @author 马磊
 * @since 2023-02-02
 */
@Service
public class EquipmentDataServiceImpl extends ServiceImpl<EquipmentDataMapper, EquipmentData> implements EquipmentDataService {


    @Resource
    private WebSocketServer webSocketServer;

    private static final ExecutorService POOL= Executors.newFixedThreadPool(3);

    /**
     * 分页查询设备列表
     * @param current
     * @param size
     * @param equipmentData
     * @return
     */
    @Override
    public ResModel listByPage(Integer current, Integer size, EquipmentData equipmentData) {
        Page<EquipmentData> page = new Page<>(current, size);
        LambdaQueryWrapper<EquipmentData> wrapper = new LambdaQueryWrapper<>();
        //设备号过滤查询
        wrapper.eq(StrUtil.isNotBlank(equipmentData.getEquipmentId()),EquipmentData::getEquipmentId,equipmentData.getEquipmentId());
        //时间排序
        wrapper.orderByAsc(true,EquipmentData::getTimeStamp);
        Page<EquipmentData> selectPage = baseMapper.selectPage(page, wrapper);
        //时间格式化
        for (EquipmentData record : selectPage.getRecords()) {
            record.setKey(record.getId());
            DateTimeFormatter dfDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            record.setTime(dfDateTime.format(record.getTimeStamp()));
        }
        return ResModel.success(Code.SUCCESS,selectPage);
    }

    /**
     * 保存数据
     * @param info
     * @return
     */
    @Override
    public ResModel insertData(OutputDataInfo info) {
        //保存数据
        EquipmentData equipmentData = BeanUtil.copyProperties(info, EquipmentData.class);
        equipmentData.setEquipmentId(info.getId());
        equipmentData.setTimeStamp(LocalDateTime.now());
        boolean b = save(equipmentData);
        //时间格式化
        DateTimeFormatter dfDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        equipmentData.setTime(dfDateTime.format(equipmentData.getTimeStamp()));
        //webSocketServer，给前端推送数据
        POOL.submit(()->{
            webSocketServer.sendMessage(JSONUtil.toJsonStr(equipmentData));
        });
        return b==true ? ResModel.success(Code.INSERT,b):ResModel.error(Code.UN_INSERT);
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @Override
    public ResModel deleteData(Integer id) {
        if (id==null){
            return ResModel.error(Code.UN_DELETE);
        }
        boolean b = removeById(id);
        return ResModel.success(Code.DELETE,b);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Override
    public ResModel delAllData(List<Integer> ids) {
        if (ids==null){
            return ResModel.error(Code.UN_DELETE);
        }
        boolean b = removeByIds(ids);
        return ResModel.success(Code.DELETE,b);
    }

    /**
     * 导出数据
     * @return
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) throws Exception {
        List<EquipmentData> dataList = baseMapper.selectExportData();
        ArrayList<ExcelData> excelDataArrayList = new ArrayList<>();
        for (EquipmentData equipmentData : dataList) {
            ExcelData excelData = BeanUtil.copyProperties(equipmentData, ExcelData.class);
            excelDataArrayList.add(excelData);
        }
        String fileName = "设备数据_" + System.currentTimeMillis() + ".xlsx";
        EasyExcelUtils.export2Web(response,fileName,"设备信息列表",ExcelData.class,excelDataArrayList);
    }


}
